package top.aicey.ai.sparring.filter;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class LocalDateTimeFormatSerializer  implements ObjectSerializer {

    private final String pattern;

    public LocalDateTimeFormatSerializer(String pattern) {
        this.pattern = pattern;
    }

    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if (object == null) {
            serializer.out.writeNull();
        } else {
            LocalDateTime localDateTime = (LocalDateTime)object;
            Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            SimpleDateFormat format = new SimpleDateFormat(this.pattern);
            String text = format.format(date);
            serializer.write(text);
        }
    }
}
